<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :minHeight="150"
  >
    <Spin :spinning="spinning">
      <div style="padding: 20px">
        <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
          <template #toolbar> </template>
          <!-- <template #status="{ column, record }">
          <Select style="width: 100%" :options="statusList" v-model:value="record[column.key]" />
        </template> -->
          <template #appendUsers="{ column, record }">
            <span v-for="(user, index) in record.appendUsers" :key="`${user.name}`"
              ><span style="color: blue" v-if="index != 0">，</span
              ><span style="color: blue">{{ user.realName }}</span></span
            >
          </template>
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  icon: 'ant-design:user-add-outlined',
                  tooltip: '确定',
                  onClick: handleSelectUser.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
        <SelectUser @register="registerSelectUserModal" @success="handleSuccess" />
      </div>
    </Spin>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, nextTick, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { SelectUser } from '/@/components/CustomComp';
  import { useModal } from '/@/components/Modal';
  import { Row, Col, Button, TreeSelect, Input, Spin } from 'ant-design-vue';
  import { getLinkToActions, appendUser } from '/@/api/process/process';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isArray } from '/@/utils/is';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table';

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      SelectUser,
      Row,
      Col,
      Button,
      Input,
      BasicTable,
      TableAction,
      Spin,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage, createConfirm } = useMessage();
      const { t } = useI18n();
      const myActionId = ref(0);
      const spinning = ref(false);

      const columns: BasicColumn[] = [
        {
          title: '节点',
          dataIndex: 'inName',
          ellipsis: true,
          // slots: { customRender: 'title' },
          resizable: true,
          customRender: ({ record }) => {
            return `${record.jobName}:${record.title}`;
          },
        },
        {
          title: '原用户',
          dataIndex: 'userRealName',
          ellipsis: true,
          resizable: true,
        },
        {
          title: '追加的用户',
          dataIndex: 'appendUsers',
          ellipsis: true,
          resizable: true,
          slots: { customRender: 'appendUsers' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 150,
          ellipsis: true,
          resizable: true,
          slots: { customRender: 'status' },
        },
      ];
      const [registerTable, { reload, setTableData, deleteTableDataRecord }] = useTable({
        title: '',
        columns,
        searchInfo: {
          op: 'search',
        },
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        immediate: false,
        pagination: false,
        canResize: false,
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
        rowKey: 'id',
      });

      const actionList: Recordable = ref([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '60%' });
        console.log('data', data);
        myActionId.value = data.myActionId;

        // await nextTick();
        // setTimeout(async () => {
        actionList.value = await getLinkToActions({ myActionId: myActionId.value });
        setTableData(actionList.value);
        // }, 500);
      });

      const [registerSelectUserModal, { openModal }] = useModal();
      let oldData: Recordable[] = [];
      const handleSuccess = (data) => {
        actionList.value.forEach((action) => {
          if (action.id == curActionId) {
            action.appendUsers = data.map((item) => {
              return {
                name: item.name,
                realName: item.realName,
              };
            });
          }
        });
        // setTableData(actionList.value);
        oldData = data || [];
      };

      let curActionId = 0;
      const handleSelectUser = (record) => {
        curActionId = record.id;
        openModal(true, { users: oldData });
      };

      const getTitle = '追加人员';

      async function handleSubmit() {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确认要追加人员么'),
          onOk: async () => {
            const actions = actionList.value.map((item) => {
              return {
                id: item.id,
                users: item.appendUsers.map((it) => {
                  return { name: it.name, realName: it.realName };
                }),
              };
            });
            const params = {
              myActionId: myActionId.value,
              actions,
            };
            spinning.value = true;
            await appendUser(params);
            spinning.value = false;
            createMessage.success('操作成功');
            emit('success');
            closeModal();
          },
        });

        // try {
        //   const values = await validate();
        //   console.log('values', values);
        //   setModalProps({ confirmLoading: true });
        //   const formData = Object.assign({}, dataRef, values);
        //   formData.units =
        //     formData.divUnit && formData.divUnit.length ? formData.divUnit.join(',') : '';
        //   formData.users = dataRef['userNames'];
        //   if (isArray(formData['roles'])) {
        //     formData.roles = formData['roles'].join(',');
        //   }
        //   console.log('formData', formData);
        //   if (formData.units == '' && formData.users == '' && formData.roles == '') {
        //     createMessage.success('请选择单位或用户');
        //     return;
        //   }
        //   let data = await getDistribute(formData);
        //   if (data.res == 0) {
        //     createMessage.success(t('common.opSuccess'));
        //   }
        //   closeModal();
        //   emit('success');
        // } finally {
        //   setModalProps({ confirmLoading: false });
        // }
      }

      return {
        registerModal,
        getTitle,
        handleSubmit,
        registerSelectUserModal,
        handleSelectUser,
        handleSuccess,
        registerTable,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        spinning,
      };
    },
  });
</script>
